package dai.samples.shiro.controller;

import com.alibaba.fastjson.JSON;
import dai.samples.shiro.config.Constants;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.eis.SessionDAO;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

/**
 * 会话管理的相关内容
 */
@RestController
public class SessionController {

    @Autowired
    private SessionDAO sessionDAO;


    /**
     * 查看活跃的会话列表
     * @return
     */
    @RequestMapping("sessionList")
    public String sessionList() {
        Collection<Session> sessions =  sessionDAO.getActiveSessions();
        String sessionStr = JSON.toJSONString(sessions);
        return sessionStr;
    }

    /**
     * 尝试移除一些会话
     * @param sessionId
     * @return
     */
    @RequestMapping("/{sessionId}/forceLogout")
    public String forceLogout(@PathVariable("sessionId") String sessionId) {
        try {
            Session session = sessionDAO.readSession(sessionId);
            if (session != null) {
                session.setAttribute(Constants.SESSION_FORCE_LOGOUT_KEY, Boolean.TRUE);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "forceLogout";
    }

    /**
     * 获得会话信息
     * @return
     */
    @RequestMapping("getSessionInfo")
    public String getSessionInfo() {
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        Map map = new HashMap();
        map.put("会话ID",session.getId());
        map.put("会话主机",session.getHost());
        map.put("过期时间",session.getTimeout());
        map.put("创建时间",session.getStartTimestamp());
        map.put("最后访问时间",session.getLastAccessTime());
        map.put("创建时间",session.getStartTimestamp());
        return JSON.toJSONString(map);
    }

}
